import 'dart:async';
import 'dart:core';

extension ThrottleDebounce on Function {
  /// 支持0-1个参数，实现防抖
  /// func  需要执行的逻辑
  /// delay 设置延迟时长
  useDebounce(Function? func, {Duration delay = const Duration(milliseconds: 500)}) {
    Timer? debounce;
    // 2、可选位置参数
    target([arg]) {
      // 1、为空则不会执行取消定时器的操作
      debounce?.cancel();
      debounce = Timer(delay, () {
        // 3、判断是否传入参数
        arg != null ? func?.call(arg) : func?.call();
      });
    }

    return target;
  }

  /// 节流
  /// arg 参数
  /// milliseconds 延时执行
  void Function() useThrottle(dynamic arg, {int milliseconds = 500}) {
    bool isAllowed = true;
    Timer? throttleTimer;
    return () {
      if (!isAllowed) return;
      isAllowed = false;
      arg != null ? this.call(arg) : this.call();
      throttleTimer?.cancel();
      throttleTimer = Timer(Duration(milliseconds: milliseconds), () {
        isAllowed = true;
      });
    };
  }

  void Function([dynamic arg]) useThrottle2([int milliseconds = 500]) {
    bool isAllowed = true;
    Timer? throttleTimer;
    return ([arg]) {
      if (!isAllowed) return;
      isAllowed = false;
      arg != null ? this.call(arg) : this.call();
      throttleTimer?.cancel();
      throttleTimer = Timer(Duration(milliseconds: milliseconds), () {
        isAllowed = true;
      });
    };
  }
}
